<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/4/11
 * Time: 22:01
 */
namespace App\Http;

use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Redis;

class Helper
{
    public static function getUserIdByName($username)
    {
        return Redis::get(self::getUserIdKey($username));
    }

    public static function getUserNameById($uid)
    {
        return Redis::get(self::getUserKey($uid));
    }
    /**
     * 返回自增长的userid
     * @return mixed
     */
    public static function getAutoUserId()
    {
        return Redis::command('incr',['global:userid']); //自增长的useid
    }

    /**
     * 获取post的自增id
     * @return mixed
     */
    public static function getAutoPostId()
    {
        return Redis::command('incr',['global:postid']); //自增长的postid
    }

    /**
     * 返回用户key
     * @param $userId
     * @return string
     */
    public static function getUserKey($userId)
    {
        return 'user:userid:'.$userId.':username';
    }

    /**
     * 返回用户密码key
     * @param $userId
     * @return string
     */
    public static function getUserPassKey($userId)
    {
        return 'user:userid:'.$userId.':password';
    }

    /**
     * 返回用户id key
     * @param $username
     * @return string
     */
    public static function getUserIdKey($username)
    {
        return 'user:username:'.$username.':userid';
    }

    /**
     * 检测用户已经登录，跳转到用户界面
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public static function checkLogin()
    {
        return Cookie::get('user') ? 1 : 0;
    }

    /**
     * 生成随机字符串
     * @return string
     */
    public static function randSercet()
    {
        $str = '1234567890sdhajskdjasdkjasjdaksjdlkajsdljkasdlkjasdgjhdsfkhasldjaslkdjalskd';
        return substr(str_shuffle($str),0,16);
    }

    public static function formattime($time)
    {
        $sec = time() - $time;
        if($sec >= 86400)
        {
            return floor($sec/86400).'天';
        }
        elseif($sec > 3600)
        {
            return floor($sec/3600).'小时';
        }
        elseif($sec > 60)
        {
            return floor($sec/60).'分钟';
        }
        else
        {
            return $time.'秒';
        }
    }

    /**
     * 返回码表对应信息
     * @param $num
     * @return string
     */
    public static function urlTrans($num)
    {
        $table = self::getRandomStr();
        $res = '';
        while ($num > 62)
        {
            $res = $table[$num%62].$res;
            $num = floor($num/62);
        }
        if($num > 0)
        {
            $res = $table[$num].$res;
        }

        return $res;
    }

    /**
     * 返回一个62位的随机码表，用户url转换获取信息
     * @return array
     */
    public static function getRandomStr()
    {
        $str = '12312323jdlkjasdlkjasldkjajsd546840596804958jldksjflkjsdfl90&h';
        $s = str_split(str_shuffle($str));

        return $s;
    }
}